# coding=utf-8
# encoding=utf-8
import os
import base64
import Model
from kafkaModel import *

KAFKA_HOST = "127.0.0.1"
KAFKA_PORT = 9092
KAFKA_TOPIC = "foobar"


def count_empty_dir():
    rootdir = u'E:\\Csharpproject\\Monitor\\Monitortest\\Monitortest\\bin\\Debug\\savePic'
    dirList = []
    fileswhole = os.walk(rootdir)
    countNum = 0
    for root, dirs, files in fileswhole:
        if len(files) == 0:
            if root == rootdir:
                continue
            else:
                print(root)
            countNum += 1
    return countNum


def change_file_name():
    rootdir = u'E:\\Csharpproject\\Monitor\\Monitortest\\Monitortest\\bin\\total\\'
    fileswhole = os.walk(rootdir)
    for root, dirs, files in fileswhole:
        for file in files:
            filename = os.path.join(root, file)
            if filename.__contains__('.jpg'):
                waitprint = file.split(u'-')
                os.rename(filename, os.path.join(root, waitprint[0] + waitprint[1] + '.jpg'))


def get_file_all(root_dir=None):
    files_whole = os.walk(root_dir)
    picList = []
    for root, dirs, files in files_whole:
        if files is not None and len(files) > 0:
            if files[0].__contains__('jpg'):
                filename = files[-1].replace(root, '')
                # print(files[-1])
                if files[-1].__contains__(u'后'):
                    # 将文件移动到目标文件夹中，可替换为其他函数
                    # shutil.move(os.path.join(root, files[0]), dirback + filename)
                    picList.append(os.path.join(root, files[0]))
    return picList


if __name__ == '__main__':
    kafka_producer = PicKafkaProducer(kafka_host=KAFKA_HOST, kafka_port=KAFKA_PORT, kafka_topic=KAFKA_TOPIC)
    for pic_dir in get_file_all(root_dir=r'E:\Csharpproject\Monitor\Monitortest\Monitortest\bin\Debug\savePic'):
        pic_dir_split = pic_dir.split('\\')
        pic_info = str(pic_dir_split[-1]).split('-')
        pic_type = str(pic_dir).split('.')[-1]
        with open(pic_dir, "rb") as f:
            # b64encode是编码，b64decode是解码
            base64_data = base64.b64encode(f.read())
            # base64.b64decode(base64data)
            # print(base64_data)
            pic_data_model = Model.PictureJsonData(datetime=pic_info[2], image_base64=base64_data,
                                                   image_dir=pic_dir, file_type=pic_type)
            print(pic_data_model.toJson())

            # import time
            # time.sleep(500)
            # print(pic_dir_split[-1])
    # change_file_name()
    # print(count_empty_dir())
